#include "system.h"

int rfidDataAvailable = 0;
int tagLength = 0;
byte rfidTag[12] = {0,0,0,0,0,0,0,0,0,0,0,0};

void initUart2()
{
	//Mode Register Data
	//_UFRZ			//Aparently not implemented in this chip
	U2MODEbits.USIDL  = 0;	//Stop in Idle Mode Bit (Read/Write)
	U2MODEbits.IREN   = 0;	//IrDA Encoder/Decoder Enable (Read/Write)
	U2MODEbits.RTSMD  = 0;	//Simplex or Flow Control Modes (Read/Write)
	//_ALTO			//Apparently not implemented in this chip
	U2MODEbits.UEN    = 0;	//Uart Function Enable Bits (Read/Write)
	U2MODEbits.WAKE   = 0;	//Wake-up on Start Bit Dectect (Read/Write)
	U2MODEbits.LPBACK = 0;	//Loopback Mode Select Bit (Read/Write)
	U2MODEbits.ABAUD  = 0;	//Auto-Baud Enable Bit (Read/Write)
	U2MODEbits.RXINV  = 0;	//Receive Polarity Inversion Bit (Read/Write)
	U2MODEbits.BRGH   = 0;	//High Baud Rate Select (Read/Write)
	U2MODEbits.PDSEL  = 0;	//Parity and Data Selection Bits (8 data, no parity) (Read/Write)
	U2MODEbits.STSEL  = 0;	//Stop Selection (1 Stop Bit) (Read/Write)

	//Status Register Data
	U2STAbits.UTXISEL1 = 0;	//Transmission Interrupt Mode Bits (Read/Write)
	U2STAbits.UTXINV   = 0;	//Transmit Polarity Inversion Bit (Read/Write)
	U2STAbits.UTXBRK   = 0;	//Transmit Break Bit (Read/Write)
	//U2STAbits.UTXBF		//Transmit Buffer Full Status Bit (Read)
	//U2STAbits.TRMT			//Transmit Shift Register is Empty (Read)
	U2STAbits.URXISEL  = 0;	//Receive Interrupt Mode Selection Bits (Read/Write)
	U2STAbits.ADDEN    = 0;	//Address Character Detect Bit (Read/Write)
	//U2STAbits.RIDLE		//Receiver Idle Bit (Read)
	//U2STAbits.PERR			//Parity error Status Bit (Read)
	//U2STAbits.FERR			//Framing error Status Bit (Read)
	//U2STAbits.OERR			//Receive Buffer Overrun Error Status Bit (Read)
	//U2STAbits.URXDA		//Receive Buffer Data Available Bit (Read)

	//UART Receive Register
	//U2RXREG		//Data Bits of the Received Character (Read)

	//UART Transmit Register
	//U2TXREG		//Data Bits of the Transmitted Character (Write)

	//UART Baud Rate Generator Register
	U2BRG = 103;//21 for 6.8MHz FCLK//(SYSCLOCK/(16*UARTBAUD))-1; //The math of this function isn't working,
											 //so the value has been hand calculated and coded in

	//Uart enable bits
	U2MODEbits.UARTEN = 1;	//Enable UART Part of Mode Register
	U2STAbits.UTXEN  = 1;	//Enable TX of UART Part of Status and Control Register
	_U2RXIE = 1;	//Receive Interrupt Enable
	_U2RXIF = 0;	//Clear Receive Interrupt Flag
}

//Interrupt Functions
void __attribute__((__interrupt__, auto_psv)) _U2RXInterrupt(void)
{
	char dummy; 

	dummy = U2RXREG;

	if(!rfidDataAvailable)
	{
		rfidTag[tagLength++] = dummy;

		if(tagLength == RFIDPACKET)
		{
			rfidDataAvailable = 1;
			LED2 =0;
			tagLength = 0;
		}
	}

	_U2RXIF = 0;	//Reset Interrupt Flag
}

void __attribute__((__interrupt__, auto_psv)) _U2TXInterrupt(void)
{
	//Unused
}
